var fetchLoopTimer = null;

var hidden, visibilityChange; 

if (typeof document.hidden !== "undefined") { // Opera 12.10 and Firefox 18 and later support 
  hidden = "hidden";
  visibilityChange = "visibilitychange";
} else if (typeof document.msHidden !== "undefined") {
  hidden = "msHidden";
  visibilityChange = "msvisibilitychange";
} else if (typeof document.webkitHidden !== "undefined") {
  hidden = "webkitHidden";
  visibilityChange = "webkitvisibilitychange";
}


var operationBtn = function(){
      var selector="#op-btn";

      $("#table--data")
      .change(function() {
        selectedItems = getCheckBox();
        if (selectedItems.length > 0) {
    	  show(selectedItems.length);
    	  // $('#selected_ids').val(selectedItems);
        } else {
    	  hidden();
        }
       })

        function hidden(){
          $(selector).prop( "hidden","True");
        }

        function show(length){
          $("#op-btn").removeAttr('hidden');
          if (length > 1)
          {
            $("li.nav-item div.dropdown-menu button.single-select").prop("hidden", true);
          } else {
            $("li.nav-item div.dropdown-menu button.single-select").removeAttr("hidden");
          }
         }
}

var table = new Tabulator("#table--data", {
       // data:tabledata,
       tooltips:true,
       height:"80%",
       layout:"fitDataFill",
       rowFormatter:function(row){
        // if(row.getData().age >= 18){
            row.getElement().classList.add("table-striped"); //mark rows with age greater than or equal to 18 as successful;
        // }
       },
       cellEdited:function(cell){
    	       data = cell.getData()
    	       log_id = data['id']
    	       comments = data['comments']
               formData = new FormData(); 
               var token = $('input[name="csrfmiddlewaretoken"]').attr('value');
               formData.append('csrfmiddlewaretoken', token);
               formData.append("comments", comments); 
               $.ajax({
                     type: "POST",
                     url: '/comment_update/'+log_id, 
                     data: formData, 
                     cache: false, 
                     async: true, 
                     processData: false, 
                     contentType: false,
                     success: function(returndata) {
                        console.log(returndata);
                        if (returndata['status']==0){
                            console.log("Comments update successfully.")
                            startFetchLoop()
                        }
                     },
                     error: function(returndata) {
                          console.log(returndata);
                          startFetchLoop()
                     }
                 });
       },
       cellEditing:function(cell){
        // Cell in editting
    	stopFetchLoop()
       },
       cellEditCancelled:function(cell){
	// Retrigger the timer post edit.
        startFetchLoop()
       },
       layout:"fitColumns",
       pagination:"local",
       paginationSize:10,
       paginationSizeSelector:[3, 6, 10, 20, 40],
       columns:[
         {formatter:"rowSelection", titleFormatter:"rowSelection", hozAlign:"center", width:5, headerSort:false, cellClick:function(e, cell){
           cell.getRow().toggleSelect();
         }},
         {title:"File", field:"filename", formatter:function(cell, formatterParams, onRendered){
    	     log_id = cell.getRow().getData()['id']
	     shared = cell.getRow().getData()['shared'];
	     log_name = cell.getValue()
	     if (shared){
                 return "<a  href=\"/sharetrack/"+log_id+"\"><i class=\"fas fa-link fa-xs\"></i></a> <a class=\"analyze_ready\" href=/analyze/" + log_id + " >"+log_name+ "</a>"
                 // return "<span class=\"text-sm badge badge-pill badge-info\">Shared</span><a class=\"analyze_ready\" href=/analyze/" + log_id + " >"+log_name+ "</a>"
	     } else {
                 return "<a  class=\"analyze_ready\" href=/analyze/" + log_id + " >"+log_name+ "</a>"
	     }
     }, width:400},
         {title:"Comments", field:"comments",  editor:"textarea"},
         {title:"Version", field:"version", },
         {title:"Build", field:"build", },
         {title:"Serial Number", field:"serialnumber", },
         {title:"Status", field:"status", formatter:function(cell, formatterParams, onRendered){

	     c = cell.getValue()
	     if (c.startsWith("Extraction")){
		return "<span class=\"text-success\">" + c + "</span>";
	     } else if (c.startsWith("Extracting")){
		return "<span class=\"text-warning\">" + c + "</span>";
	     } else if (c.startsWith("Invalid")){
		return "<span class=\"text-danger\">" + c + "</span>";
	     } else if (c.startsWith("Log")){
		return "<span class=\"text-warning\">" + c + "</span>";
	     } else if(c.startsWith("Ready")){
		return "<span class=\"text-success\">" + c + "</span>";
	     } else {
                return c; //return the contents of the cell;
	     }
},},
         {title:"Techsupp Type", field:"techsupptype", },
	       {title:"Post Time", field:"postime", formatter:"datetime", sorter:"datetime", sorterParams: {
		       format:"YYYY-MM-DD hh:mm:ss"
	       } },
       ],
});

function getCheckBox(){
    // var selectedItems = table.getSelectedRows()
    var selectedItems = table.getSelectedData()
    return selectedItems
}

function toggleCheckBox(){
    // var selectedItems = table.getSelectedRows()
    var selectedItems = table.getSelectedData()
    // return selectedItems
    selectedItems.forEach((entry)=>{
        console.log("Toggle checkedBox ->: "+entry.id)
		table.deselectRow(entry.id)
    })
}

function recoverCheckBox(selectedItems){
    selectedItems.forEach((entry)=>{
        // console.log(entry)
        console.log("Recover checkedBox ->: "+entry.id)
        table.selectRow(entry.id)
    })
}

function fetchData(callback) {
  $.get("/fetch/", function(data, status){

     prev_hash = $('input[name="table-hash"]').attr('value');	
     tableData = data['data']
     hash = objectHash.sha1(tableData);
     $('input[name="table-hash"]').val(hash)
     if (prev_hash==hash){
       console.log(prev_hash+"->"+hash);
       console.log("No need to update the table.");

     } else {
       // handle contex
       var checkedBox = getCheckBox()
       table.replaceData(tableData)
             .then(function(){
                      recoverCheckBox(checkedBox)
                  })
     }
      
     if (callback!=null){
         callback();
     }
  });
}

function checkNeedRefresh(){
    var needRefresh = false;
    var data = table.getData();
    data.forEach((entry)=>{
      if (entry["status"] != "Ready"){
        needRefresh = true
      }
    })
    return needRefresh
}

function startFetchLoop() {
    fetchLoopTimer = setInterval(getLoopTimer(), 2000);
};
    
    
function stopFetchLoop() {
    if ( fetchLoopTimer !== null ){
        clearInterval(fetchLoopTimer);
        console.log("clear timer.")
    }
    fetchLoopTimer = null;
};

function getLoopTimer(){
    return function(){
        // # To do: should check status of the table.
        // check status
        needRefresh=checkNeedRefresh();
        console.log("Table updated: "+needRefresh);
        if (needRefresh){
            fetchData();
        }
    }
};

var opBtn = new operationBtn()
fetchData();
startFetchLoop();


function triggerAnalyze(log_id, callback) {
  $.getJSON('/analyze-operation/' + log_id, function(data){
    console.log(data);
    if (data['status'] == "0"){
        popInfo("Start analyzing the log from backend.");
    } else {
        popError("Failed to start analyzing the log from backend.");
    }
  });
	setTimeout(callback, 1000);
};

function contextClean(){
    $("#op-btn").prop( "hidden","True");
    $('#selected_ids').val("");
};

function popInfo(s){
    console.log(s);
};

function popSucc(s){
    console.log(s);
};

function popError(s){
    console.log(s);
};

var deleteLogs = function () {
  checkedBoxes = getCheckBox()
  var log_ids = []
  console.log(checkedBoxes)
  checkedBoxes.forEach(function(entry){
	  // console.log(entry)
	  log_ids.push(entry.id)
  })
  log_ids = log_ids.join(",")
  // console.log(log_ids)
  // var log_ids = $('#selected_ids').val();
  // console.log(log_ids);
  $.getJSON('/deletelogs/' + log_ids, function(data){
    if (data['status'] == "0"){
        popSucc("Remove the log file successfully.");
        /* hide the button after removing the logs.
         */
        $("#op-btn").prop( "hidden","True");
	toggleCheckBox()
        fetchData();
    } else {
        popError("Error happened when removing the logs, please refresh.");
    }
  })
};

function FileChangeFn(event) {
    $('.opst_txt').text('Please reselect the file.');
    var event = event || window.event,
        ofile = $("#id_file").get(0).files[0],
        otype = ofile.type || 'File type access failed.',
        oname = ofile.name,
        osize = ofile.size / 1054000,
        ourl = window.URL.createObjectURL(ofile); 
    if ( otype.includes("gzip") ){
      PostFileInfoBox(otype, osize, oname)
    } else {
      PostFileErrBox()
    }
};

function PostFileBoxClean(){
  $("#label-input-file").html("Choose file");
  // $("#id_file").val("");
  /*
   Clean tag area
  */ 
  $('#file_type').text("");
  $('#file_size').text("");
  $('#file_type').removeClass("badge-info").removeClass("badge-danger");
  /*
   Clean progress bar
  */
  $("#speed").removeClass('bg-success').addClass('bg-info');
  $("#speed").html("0%").css("width", "0%");
  $('#upload-progress-bar').prop( "hidden","True" )
  $('#upload-btn').addClass('btn-warning').prop('disabled', true);
}

function PostFileInfoBox(otype, osize, oname){
  // Clean Contex
  PostFileBoxClean();
  $('#file_type').addClass("badge-info");
  $('#file_type').text("File Type：" + otype);
  // console.log(otype);
  $('#file_size').text("Size: " + osize.toFixed(2) + "MB.");
  $('#label-input-file').html(oname);
  $('#upload-btn').removeClass('btn-warning').addClass('btn-success').prop('disabled', false);
}

function PostFileErrBox(){
  // Clean Contex
  PostFileBoxClean();
  $('#file_type').addClass("badge-danger");
  $('#file_type').text("ONLY <tar.gz/tgz> support.");
  // $("#id_file").val("");
}


function OnProgRess(event) {
    var event = event || window.event;
    var loaded = Math.floor(100 * (event.loaded / event.total)); 
    $("#speed").html(loaded + "%").css("width", loaded + "%");
};


function UploadFileFn() {
    $('#upload-progress-bar').removeAttr('hidden');
    $('.progress').show();
    var oFile = $("#id_file").get(0).files[0],
    formData = new FormData(); 
    xhr = $.ajaxSettings.xhr(); 
    /* 
     get csrf token.
    */
    var token = $('input[name="csrfmiddlewaretoken"]').attr('value');
    formData.append('csrfmiddlewaretoken', token);
    formData.append("file", oFile); 
    $.ajax({
        type: "POST",
        url: '/', 
        data: formData, 
        cache: false, 
        async: true, 
        processData: false, 
        contentType: false,
        xhr: function() {
            if (OnProgRess && xhr.upload) {
                xhr.upload.addEventListener("progress", OnProgRess, false);
                return xhr;
            }
        },
        success: function(returndata) {
            $("#speed").removeClass('bg-info').addClass('bg-success').html("Submit Success");
            $("#uploadmodal").modal('toggle');
            popSucc("File submitted successfully.");
            logId = returndata['log_id'];
            // triggerAnalyze(logId, fetchData);
            fetchData();
            cleanPostSubmission();
        },
        error: function(returndata) {
	    console.log(returndata)
            $("#speed").html("Submit Failed");
            popError("File submitted failed.");
        }
    });

    $('#upload-btn').prop('disabled', true).removeClass('btn-primary').addClass('btn-secondary')
};

function cleanPostSubmission(){
  /* 
   Clean file input box
  */
  $("#label-input-file").html("Choose file");
  $("#id_file").val("");
  /*
   Clean tag area
  */ 
  $('#file_type').text("");
  $('#file_size').text("");
  /*
   Clean progress bar
  */
  $("#speed").removeClass('bg-success').addClass('bg-info');
  $("#speed").html("0%").css("width", "0%");
  $('#upload-progress-bar').prop( "hidden","True" )
}

function handleVisibilityChange() {
  if (document[hidden]) {
    if (fetchLoopTimer !== null) {
      stopFetchLoop();
    }
  } else {
    // console.log("Tab reactivate")
    if (fetchLoopTimer == null) {
      startFetchLoop();
    } 
  }
}


$(document).ready(function(){

    $('.modal').on('show.bs.modal', function (e) {
        stopFetchLoop();
    });

    $('.modal').on('hide.bs.modal', function (e) {
        startFetchLoop();
    });

    document.addEventListener("visibilitychange", handleVisibilityChange, false);

    $('#shareModal').on('show.bs.modal', function (e) {
	    var selectedItems = table.getSelectedData()
	    log_id = selectedItems[0].id
	    shareAddr = $(location).attr('href')+"shared/"+log_id
	    $('input[name="share-addr"]').val(shareAddr)
	    shared = selectedItems[0].shared
	    if (shared){
		console.log("Log already been shared.")
		$('button[name="share-btn"]').text("Shared")
		$('button[name="share-btn"]').removeClass("btn-info")
		$('button[name="share-btn"]').addClass("btn-success")
		$('button[name="share-btn"]').prop('disabled', true)
	    }
		
    });

});

function toggleShare(){
    var selectedItems = table.getSelectedData()
    var log_id = selectedItems[0].id
    $.get("/genshare/"+log_id, function(data, status){
	    // console.log(data);
	    if (data['error'] ==0){
		console.log("Share log successfully.")
		$('button[name="share-btn"]').text("Shared")
		$('button[name="share-btn"]').removeClass("btn-info")
		$('button[name="share-btn"]').addClass("btn-success")
	        $('button[name="share-btn"]').prop('disabled', true)
                fetchData();
	    } else {
		$('input[name="share-addr"]').val("Failed to share, internal error.")
	    }
    })

}
